package com.icez.videoplay.core

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.webkit.JavascriptInterface
import android.widget.FrameLayout
import androidx.core.view.postDelayed
import com.google.android.youtube.player.YouTubeInitializationResult
import com.google.android.youtube.player.YouTubePlayer
import com.icez.base_util_library.LogUtil
import com.icez.base_util_library.ResourcesUtil
import com.icez.bwebviewlibrary.BWebView
import com.icez.bwebviewlibrary.BWebView.Companion.ANDROID_ASSET_INDEX
import com.icez.bwebviewlibrary.bridge.JsBridgeInterface
import com.icez.videoplay.*
import com.icez.videoplay.enum.VideoPlayType
import com.icez.videoplay.lpi.VideoPlayInterface
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


/**
 * @sample 视频播放控件
 */
class VideoPlayLayout : FrameLayout, VideoPlayInterface {

    companion object {
        var FBURL = "https://www.facebook.com/facebook/videos/"
    }

    private var mVideoPlayType: VideoPlayType? = null
    private var mYouTubePlayer: YouTubePlayer? = null
    private var mWebview: BWebView? = null

    private var isInterceptTouch: Boolean = true

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {

        setBackgroundColor(Color.TRANSPARENT)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()

    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return isInterceptTouch
    }

//    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
//        return true
//    }

    /**
     * @sample 初始YouTube
     * @param activity Activity
     * @param apiKey api钥匙
     * @param videoId 视频id
     * @param initSuccess 初始化成功
     * @param initFail 初始化失败
     */
    private fun initYT(
        activity: Activity,
        apiKey: String,
        videoId: String,
        initSuccess: ((width: String, height: String) -> Unit)?,
        initFail: ((errorMsg: String) -> Unit)?
    ) {
        removeAllViews()
        val playerView = FrameLayout(context)
        val lp = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
        )
        lp.gravity = Gravity.CENTER
        playerView.layoutParams = lp
        playerView.setId(R.id.youtube_framelayout)
        addView(playerView)
//        postDelayed(500) {
        YoutubePlayManager.instance.initConfig(
            activity,
            apiKey,
            object : YouTubePlayer.OnInitializedListener {
                override fun onInitializationSuccess(
                    provider: YouTubePlayer.Provider, player: YouTubePlayer,
                    wasRestored: Boolean
                ) {
                    mYouTubePlayer = player


                    mYouTubePlayer?.setFullscreen(false)
                    mYouTubePlayer?.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS)
                    mYouTubePlayer?.setPlayerStateChangeListener(object :
                        YouTubePlayer.PlayerStateChangeListener {
                        override fun onLoading() {

                        }

                        override fun onLoaded(p0: String?) {
                            if (initSuccess != null) {
                                initSuccess("", "")
                            }
                        }

                        override fun onAdStarted() {

                        }

                        override fun onVideoStarted() {

                        }

                        override fun onVideoEnded() {

                        }

                        override fun onError(p0: YouTubePlayer.ErrorReason?) {
                            Log.e("icez", "p0 " + p0.toString())
                            if (initFail != null) {
                                initFail(p0.toString())
                            }
                        }
                    }
                    )

                    mYouTubePlayer?.loadVideo(videoId)

                }

                override fun onInitializationFailure(
                    p0: YouTubePlayer.Provider?,
                    p1: YouTubeInitializationResult?
                ) {
                    if (initFail != null) {
                        initFail(p1.toString())
                    }
                }

            })
//        }

    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)

    }

    fun dpToPx(dps: Float): Float {
        val scale = context.resources.displayMetrics.density
        return (dps * scale + 0.5f)
    }

    /**
     * @sample 初始fb
     * @param appId appid
     * @param videoId 视频id
     * @param initSuccess 初始化成功
     * @param initFail 初始化失败
     *
     */
    private fun initFB(
        fbUrl: String, initSuccess: ((width: String, height: String) -> Unit)?,
        initFail: ((errorMsg: String) -> Unit)?, width: Float? = 0f, height: Float? = 0f
    ) {
        removeAllViews()
        mWebview = BWebView(context)
        if (width != 0f && height != 0f) {
            mWebview?.layoutParams =
                FrameLayout.LayoutParams(dpToPx(width ?: 0f).toInt(), dpToPx(height ?: 0f).toInt())

        }
        mWebview?.settings?.mediaPlaybackRequiresUserGesture = false
        mWebview?.setBackgroundColor(0)
        addView(mWebview)

//        postDelayed(500) {

        mWebview?.setJsBridge(object : JsBridgeInterface {
            @JavascriptInterface
            fun onStartPlaying(e: String, width: String, height: String) {
                LogUtil.E("fb onStartPlaying" + " width: " + width + " height: " + height)
                if (initSuccess != null) {
                    postDelayed(500) {
                        unMute()
                    }
                    initSuccess(width, height)
                }
            }

            @JavascriptInterface
            fun onStartBuffering(e: String) {
                LogUtil.E("fb onStartBuffering")
            }

            @JavascriptInterface
            fun onPaused(e: String) {
                LogUtil.E("fb onPaused")
            }

            @JavascriptInterface
            fun onError(e: String) {
                LogUtil.E("fb onError")
                if (initFail != null) {
                    initFail(e)
                }
            }

            @JavascriptInterface
            fun onFinishPlaying(e: String) {
                LogUtil.E("fb onFinishPlaying")
            }

            @JavascriptInterface
            fun onFinishBuffering(e: String) {
                LogUtil.E("fb onFinishBuffering")
            }
        }, "FacebookInterface")
        mWebview?.loadWeb(fbUrl,
            onPageFinishedListenner = {

            },
            onPageErrorListenner = {
                if (initFail != null) {
                    initFail("網頁加載")
                }
            })


    }

    /**
     * @sample 初始fb
     * @param appId appid
     * @param videoId 视频id
     * @param initSuccess 初始化成功
     * @param initFail 初始化失败
     *
     */
    private fun initYouTuBeWeb(
        youtubeUrl: String, initSuccess: ((width: String, height: String) -> Unit)?,
        initFail: ((errorMsg: String) -> Unit)?, width: Float? = 0f, height: Float? = 0f
    ) {
        removeAllViews()
        mWebview = BWebView(context)
        if (width != 0f && height != 0f) {
            mWebview?.layoutParams =
                FrameLayout.LayoutParams(dpToPx(width ?: 0f).toInt(), dpToPx(height ?: 0f).toInt())

        }
        mWebview?.settings?.mediaPlaybackRequiresUserGesture = false
        mWebview?.setBackgroundColor(0)
        addView(mWebview)

//        postDelayed(500) {

        mWebview?.setJsBridge(object : JsBridgeInterface {
            @JavascriptInterface
            fun onStartPlaying(width: String, height: String) {

                if (initSuccess != null) {
//                    postDelayed(500){
//                        unMute()
//                    }
                    setPlayVideo()

                    initSuccess(width, height)
                }
            }


            @JavascriptInterface
            fun onError(e: String) {
                LogUtil.E("youtube onError")
                if (initFail != null) {
                    initFail(e)
                }
            }

        }, "YouTuBeInterface")
        mWebview?.loadWeb(youtubeUrl,
            onProgressChangedListener = {
                LogUtil.E("网页加载完毕"+it)
//                mWebview?.toJsMethod("setIntervalPlayVideo",null)


            },
            onPageErrorListenner = {
                if (initFail != null) {
                    initFail("網頁加載")
                }
            })




    }


    private var isInitFb: Boolean = false
    private var isInitYt: Boolean = false
    override fun initConfig(
        mActivity: Activity,
        mVideoPlayType: VideoPlayType,
        apiKey: String,
        videoId: String,
        fbUrl: String,
        initSuccess: ((width: String, height: String) -> Unit)?,
        initFail: ((errorMsg: String) -> Unit)?,
        playHeight: Float?,
        playWidth: Float?
    ) {
        this.mVideoPlayType = mVideoPlayType
        when (mVideoPlayType) {
            VideoPlayType.FACEBOOK -> {
                if (isInitFb == false) {
                    isInitFb = false
                    initFB(fbUrl, initSuccess, initFail, width = playWidth, height = playHeight)
                } else {
                    setPlayVideo()
                }

            }
            VideoPlayType.YOUTUBE -> {
//                if(isInitYt==false){
                isInitYt = true
                initYT(mActivity, apiKey, videoId, initSuccess, initFail)
//                }else{
//                    setPlayVideo()
//                }

            }
            VideoPlayType.YOUTUBEWEB -> {
                if (isInitFb == false) {
                    isInitFb = false
                    initYouTuBeWeb(
                        fbUrl,
                        initSuccess,
                        initFail,
                        width = playWidth,
                        height = playHeight
                    )
                } else {
                    setPlayVideo()
                }
            }
        }

    }


    override fun setPlayVideo() {
        when (mVideoPlayType) {
            VideoPlayType.YOUTUBE -> {
                if (mYouTubePlayer != null) {
                    mYouTubePlayer?.play()
                }

            }
            VideoPlayType.FACEBOOK -> {
                mWebview?.toJsMethod("playVideo", null)
            }
            VideoPlayType.YOUTUBEWEB -> {
                mWebview?.toJsMethod("playVideo", null)
            }
        }

    }


    override fun unMute() {

        when (mVideoPlayType) {
            VideoPlayType.YOUTUBE -> {

            }
            VideoPlayType.FACEBOOK -> {
                mWebview?.toJsMethod("unMuteVideo", null)

            }
            VideoPlayType.YOUTUBEWEB ->{
                val params = ArrayList<String>()
                params.add("100")
                mWebview?.toJsMethod("setVolume",params)
            }
        }

    }

    override fun setStopVideo() {
        when (mVideoPlayType) {
            VideoPlayType.YOUTUBE -> {
                mYouTubePlayer?.pause()
            }
            VideoPlayType.FACEBOOK -> {
                mWebview?.toJsMethod("pauseVideo", null)
            }
            VideoPlayType.YOUTUBEWEB -> {
                mWebview?.toJsMethod("stopVideo", null)
            }
        }

    }


}